<template>
    <DialogBox :title="props.title" :dialogVisible="props.dialogVisible" @close="handleClose">
        <div class="application-list-container application-list-container-chat">
            <!--- 搜索栏start -->
            <div class="mb-24">
        <TopTabs @tab-click="handelTabClick" :tagsList="perTypeList">
          <div class="flex-between">
            <JustMine  class="mr-12" @change="handelJusetMine"/>
            <el-input
              v-model="searchForm.name"
              @input="handleDebounceSearch"
              placeholder="按名称搜索"
              prefix-icon="Search"
              class="w-240 search-input"
              style="min-width: 320px;"
              clearable
            />
          </div>
        </TopTabs>
      </div>
      <!-- 列表start --->
      <InfiniteScroll
        :size="applicationList.length"
        :total="paginationConfig.total"
        :page_size="paginationConfig.page_size"
        v-model:current_page="paginationConfig.current_page"
        @load="getList"
        :loading="pageLoading"
      >
        <div
          v-loading="paginationConfig.current_page === 1 && pageLoading"
          element-loading-text="正在加载..."
          style="width: 100%;height: 500px"
          v-if="pageLoading && !applicationList.length"
        ></div>
        <PageEmpty v-if="!applicationList.length && !pageLoading" :type="pageEmptyType" />
        <el-row :gutter="20">
          <el-col
            :xs="24"
            :sm="12"
            :md="8"
            :lg="8"
            :xl="8"
            v-for="(item, index) in applicationList"
            :key="index"
            class="mb-20"
          >
            <CardBoxAgent
              :title="item.name"
              :description="item.applicationDesc"
              @click="jumpToChat(item)"
              :avatar="item.imgUrl"
              :tyType="item.tyType"
              :createdByName="item.createdByName"
            />
          </el-col>
        </el-row>
      </InfiniteScroll>
            <!-- 列表end --->
        </div>
    </DialogBox>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import { ref, onMounted, reactive } from 'vue'
import useStore from '@/stores'
import { page2 } from '@/servers/ai/api/zhinengti'
import { debounce } from 'lodash'

defineOptions({ name: 'AgnetList' })
const props = defineProps({
    dialogVisible: {
        type: Boolean,
        default: false
    },
    title: {
        type: String,
        default: '选择智能体以新建对话'
    }
})

const { application, agent } = useStore()

const loading = ref(false)
const pageLoading = ref(false)
const perTypeId = ref()
const perTypeList = ref()
const pageEmptyType = ref('1')

const applicationList = ref<any[]>([])

const paginationConfig = reactive({
    current_page: 1,
    page_size: 30,
    total: 0
})

const searchForm = ref<any>({
    name: '', // 名称
    classification: '', // 分类
    authState: '' // 0-仅自己可见 1-自定义课件范围
});

const emit = defineEmits<{
    (e: 'tab-click', item: any): void;
    (e: 'tab-close'): void;
}>()

const handelTabClick = (item: any) => {
    searchForm.value.classification =   `${item.value === 'all' ? '' : item.value}`;
    searchHandle();
};

const handelJusetMine = (item: boolean) => {
    searchForm.value.authState = item
    searchHandle();
 }

function jumpToChat(item: any) {
    emit('tab-click', {
      ...item,
      access_token: item.maxTyTypeUrl,
      time: dayjs().format('MM-DD HH:mm'),
    })
    return
  // 选择智能体之后获取 application_id 和 access_token，并且增加time
  // if (item.tyType === 1) {
  //   emit('tab-click', {
  //     ...item,
  //     access_token: item.maxTyTypeUrl,
  //     time: dayjs().format('MM-DD HH:mm'),
  //   })
  //   return
  // }
  // application.asyncGetAccessToken(item.maxId, loading).then((res: any) => {
  //   emit('tab-click', {
  //     ...item,
  //     application_id: res?.data?.application_id,
  //     access_token: res?.data?.access_token,
  //     time: dayjs().format('MM-DD HH:mm'),
  //   })
  // })
}

function handleClose(){
    emit('tab-close')
}

const handleDebounceSearch = debounce(() => {
  searchHandle()
},500)

function searchHandle() {
    applicationList.value = []
    paginationConfig.current_page = 1
    paginationConfig.total = 0
    getList()
}

function getList() {
    const params: any = {
      "model": {
        state: true //获取启用状态的
       },
      "size": paginationConfig.page_size,
      "current": paginationConfig.current_page,
    }
    if (searchForm.value.name) {
      params.model.name = searchForm.value.name
      pageEmptyType.value = '2'
    } else {
      pageEmptyType.value = '1'
    }
    if (searchForm.value.classification) params.model.classification = searchForm.value.classification
    if (searchForm.value.authState) params.model.authState = 0
    pageLoading.value = true
    page2(params).then((res: any) => {
      if (res.data.isSuccess) {
        const { records, total } = res.data.data
        applicationList.value.push(...records)
        paginationConfig.total = Number(total)
      }
    })
    .finally(() => {
      pageLoading.value = false
    })
  }

onMounted( async() => {
    const options = await agent.getCategorizeOptions()
    perTypeList.value = [ {label: "全部", value: "all"}, ...options]
    perTypeId.value = 'all'
    getList()
})

</script>

<style lang="scss" scoped>
.application-list-container-chat{
  min-height: 60vh;
  position: relative;
}
</style>
